package com.ltmall.api.weixin.util;

import com.ltmall.api.bean.ClientInfo;
import com.ltmall.api.manager.AccountManager;
import com.ltmall.api.redis.RedisUtil;
import com.ltmall.api.util.HttpRequestUtil;
import com.ltmall.api.util.ImgUtil;
import com.ltmall.api.util.UUIDGenerator;
import com.wuwangkeji.homeflavor.comm.Path;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class QRCodeUtil {
	
	private static Logger logger = LogManager.getLogger(QRCodeUtil.class);
	
	public static String getShortTermQRCodeUrl(int sceneId) {

//		JSONObject accessTokenJson = HttpRequestUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token",
//				"grant_type=client_credential&appid=" + Constants.OA_APP_ID + "&secret=" + Constants.OA_APP_SECRET);
//		String accessToken = (String) accessTokenJson.get("access_token");
		String accessToken = RedisUtil.getAccessToken();
		System.out.println("accessToken:" + accessToken);
		String createTicketUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
		String createTicketParam = "{\"expire_seconds\": 2592000, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + sceneId + "}}}";
		JSONObject ticketJson = HttpRequestUtil.sendPost(createTicketUrl, createTicketParam);
		if (ticketJson.containsKey("errcode")) {
			int errcode = (Integer) ticketJson.get("errcode");
			if (errcode > 0) {
				System.out.println("获取ticket错误：" + errcode);
				logger.info("线程:" + Thread.currentThread().getId() + " 获取临时二维码ticket错误:" + errcode);
				return null;
			}
		}
		
		String ticket = (String) ticketJson.get("ticket");
		System.out.println("QRCode ticketJson:" + ticketJson);
		return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
		
	}
	
	public static String generateCompleteQRCodeImage(String qrCodeRomoteUrl, String backgroundImageLocalPath) {
		Calendar calendar = Calendar.getInstance();    
	    calendar.setTime(new Date());    
	    calendar.add(Calendar.SECOND, 2592000);    
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	    String dateString = formatter.format(calendar.getTime());
		String str = "此二维码有效期至" + dateString;
		
		BufferedImage bgImage = null;
		BufferedImage qrCodeImage = null;
		
		try {
			bgImage = ImageIO.read(new File(backgroundImageLocalPath));
			qrCodeImage = ImageIO.read(new URL(qrCodeRomoteUrl));
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("线程：" + Thread.currentThread().getId() + " IOException:" + e.getMessage());
		}
		
		if (bgImage == null || qrCodeImage == null) {
			logger.info("线程:" + Thread.currentThread().getId() + "背景图或二维码为空");
			return null;
		}
		
		Graphics2D g = bgImage.createGraphics();
		
		int width = (int) (bgImage.getWidth() * 0.3);
		int x = (int) (bgImage.getWidth() * 0.35);
		int y = (int) (bgImage.getWidth() * 0.5);
		g.drawImage(qrCodeImage, x, y,width, width, null);
		
		g.setColor(Color.white);
		g.setFont(new Font("宋体", Font.PLAIN, 25));
		g.drawString(str, x, y + width + 50);
		
		g.dispose();
		bgImage.flush();
		qrCodeImage.flush();
		
		String generateFileName = UUIDGenerator.getUUID32();
		String project = Path.project;// 项目
		String dir = Path.PLATFORM + File.separator + Path.SUBUNDERWRITING;// 路径
		File file = ImgUtil.creatFolder(project, dir, generateFileName + ".jpg");
		String filePath = file.getAbsolutePath();
		
		try {
			ImageIO.write(bgImage,"jpg", new File(filePath));
			return generateFileName + ".jpg";
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("线程：" + Thread.currentThread().getId() + " IOException:" + e.getMessage());
		}
		
		return null;
	}
	
	public static String getLimitQRCodeName(ClientInfo userInfo, AccountManager accountManager) {
		String accessToken = RedisUtil.getAccessToken();
		String createTicketUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
		String createTicketParam = Constant.getLimitQRCodeAddress(userInfo.getUserID());

		JSONObject ticketJson = HttpRequestUtil.sendPost(createTicketUrl, createTicketParam);
		if (ticketJson.containsKey("errcode")) {
			int errcode = (Integer) ticketJson.get("errcode");
			if (errcode > 0) {
				System.out.println("获取ticket错误：" + errcode);
				logger.info("线程:" + Thread.currentThread().getId() + " 获取永久二维码ticket错误:" + errcode);
				return null;
			}
		}
		String ticket = (String) ticketJson.get("ticket");
		String qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
		return compositeAvatar(qrcodeUrl, userInfo.getPhoto());		
	}
	
	public static String compositeAvatar(String qrCodeUrl, String avatarUrl) {
		BufferedImage qrImage = null;
		BufferedImage qrCodeImage = null;
		BufferedImage avatar = null;
		BufferedImage avatarThumbnail = null;
		String qrCodeName = null;
		try {
			qrCodeImage = ImageIO.read(new URL(qrCodeUrl));
			avatar = ImageIO.read(new URL(avatarUrl));
			avatarThumbnail = new BufferedImage(120, 120, avatar.getType());
			Graphics2D avatarGraphics = avatarThumbnail.createGraphics();
			//将头像背景置为透明
			avatarThumbnail = avatarGraphics.getDeviceConfiguration().createCompatibleImage(120, 120, Transparency.TRANSLUCENT);  
			avatarGraphics.dispose();
			avatarGraphics = avatarThumbnail.createGraphics();
			//圆角矩阵裁剪
			RoundRectangle2D roundRectangle2D = new RoundRectangle2D.Float(0, 0, 120, 120, 20, 20);
			//抗锯齿
			avatarGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			avatarGraphics.setClip(roundRectangle2D);
			avatarGraphics.drawImage(avatar, 0, 0, 120, 120, null);
			avatarGraphics.dispose();
			//如果直接用二维码做背景会导致头像变成黑白的，所以这边直接新生成一个背景，颜色模式用头像的
			BufferedImage compositeImage = new BufferedImage(qrCodeImage.getWidth(), qrCodeImage.getHeight(), avatar.getType());
			Graphics2D graphics = compositeImage.createGraphics();
			graphics.drawImage(qrCodeImage, 0, 0, null);
			graphics.drawImage(avatarThumbnail, ((qrCodeImage.getWidth() - avatarThumbnail.getWidth()) / 2), ((qrCodeImage.getHeight() - avatarThumbnail.getHeight()) / 2), null);
			graphics.dispose();
			String generateFileName = UUIDGenerator.getUUID32();
			String project = Path.project;// 项目
			String dir = Path.PLATFORM + File.separator + Path.SUBUNDERWRITING;// 路径
			File file = ImgUtil.creatFolder(project, dir, generateFileName + ".jpg");
			String filePath = file.getAbsolutePath();
			ImageIO.write(compositeImage,"jpg", new File(filePath));
			qrCodeName = generateFileName + ".jpg";
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("线程：" + Thread.currentThread().getId() + " IOException:" + e.getMessage());
			return null;
		} finally {
			if (qrImage != null) {
				qrImage.flush();
			}
			if (qrCodeImage != null) {
				qrCodeImage.flush();
			}
			if (avatar != null) {
				avatar.flush();
			}
			if (avatarThumbnail != null) {
				avatarThumbnail.flush();
			}
		}
		return qrCodeName;
	}
}
